package com.gccloud.design.utils;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.gccloud.feign.filter.dto.SysUser;
import com.gccloud.starter.common.constant.GlobalConst;
import com.gccloud.starter.common.exception.GlobalException;
import com.gccloud.starter.common.utils.SpringContextUtils;
import com.gccloud.starter.common.vo.R;
import com.gccloud.starter.core.dto.SysUserDataPermissionDTO;
import com.gccloud.starter.core.entity.SysUserEntity;
import com.gccloud.starter.core.vo.SysUserDataPermissionVO;
import com.gccloud.starter.feign.api.service.ISysOrgService;
import com.gccloud.starter.feign.api.service.ISysUserDataPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.springframework.core.env.Environment;
import com.gccloud.idc.security.shiro.UserUtils;

import java.util.List;

/**
 * @author liuchengbiao
 * @date 2020-07-13 15:05
 */
@Slf4j
public class WrapperUtils {
    /**
     * 这个和mp扫描的xml顺序有关
     */
    public static final SFunction<SysUserEntity, String> CREATE_BY = SysUserEntity::getCreateBy;
//    public static final SFunction<SysUserEntity, String> TENANT_ID = SysUserEntity::getTenantId;
    public static final SFunction<SysUser, String> ORG_ID = SysUser::getOrgId;
    static {
        TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), SysUser.class);
        TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), SysUserEntity.class);
    }

    public static <T> LambdaQueryWrapper<T> wrapDp(LambdaQueryWrapper<T> lambdaQueryWrapper) {
        boolean isDataPermission = Boolean.valueOf(SpringContextUtils.getBean(Environment.class).getProperty("data-permission"));
        if (isDataPermission) {
            SysUser user = UserUtils.getCurrentUser();
            String appId = SpringContextUtils.getBean(Environment.class).getProperty("appId");
            if (user == null) {
                throw new GlobalException("调用该方法必须登录", GlobalConst.Response.Code.NO_LOGIN);
            }
            // 根据用户id和应用id查询用户权限
            SysUserDataPermissionDTO dto = new SysUserDataPermissionDTO();
            dto.setUserId(user.getId());
            dto.setAppId(appId);
            R<SysUserDataPermissionVO> sysUserDataPermissionVO = SpringContextUtils.getBean(ISysUserDataPermissionService.class).getDataPermissionByUserIdAndAppId(dto);
            if (sysUserDataPermissionVO == null || sysUserDataPermissionVO.getData() == null || StringUtil.isBlank(sysUserDataPermissionVO.getData().getDataPermission())) {
                throw new GlobalException(String.format("未获取到用户权限，当前用户：%s", user.getRealName()));
            }

//        int dataPermission = user.getDataPermission();

            SysUserDataPermissionVO sysUserDataPermission = sysUserDataPermissionVO.getData();
            List<String> listOrg = sysUserDataPermission.getOrgIdList();
            String dataPermission = sysUserDataPermission.getDataPermission();

            if (String.valueOf(GlobalConst.User.DataPermission.USER).equals(dataPermission)) {
                lambdaQueryWrapper.eq((SFunction<T, String>) CREATE_BY, user.getId());
            } else if (String.valueOf(GlobalConst.User.DataPermission.ORG).equals(dataPermission)) {
                lambdaQueryWrapper.eq((SFunction<T, String>) ORG_ID, user.getOrgId());
            } else if (String.valueOf(GlobalConst.User.DataPermission.ALL).equals(dataPermission)) {
//            lambdaQueryWrapper.eq((SFunction<T, String>) TENANT_ID, user.getTenantId());
            } else if (String.valueOf(GlobalConst.User.DataPermission.ORG_AND_SON).equals(dataPermission)) {
                ISysOrgService orgService = SpringContextUtils.getBean(ISysOrgService.class);
//            Set<String> orgIdSet = orgService.getChildrenIdsByParentId(user.getOrgId());
//            orgIdSet.add(user.getOrgId());
                lambdaQueryWrapper.in((SFunction<T, String>) ORG_ID, listOrg);
            } else if (String.valueOf(GlobalConst.User.DataPermission.ORG_CUSTOM).equals(dataPermission)) {
//            ISysDataPermissionService dataPermissionService = SpringContextUtils.getBean(ISysDataPermissionService.class);
//            List<String> orgIdList = dataPermissionService.getOrgIds(user.getId());
                lambdaQueryWrapper.in((SFunction<T, String>) ORG_ID, listOrg);
            } else {
                throw new GlobalException(String.format("不支持数据权限类型: %s", dataPermission));
            }
        }
        return lambdaQueryWrapper;
    }

    public static void wrapDp(AbstractWrapper queryWrapper) {
        boolean isDataPermission = Boolean.valueOf(SpringContextUtils.getBean(Environment.class).getProperty("data-permission"));
        if (isDataPermission) {
            SysUser user = UserUtils.getCurrentUser();
            if (user == null) {
                throw new GlobalException("调用该方法必须登录", GlobalConst.Response.Code.NO_LOGIN);
            }
            String appId = SpringContextUtils.getBean(Environment.class).getProperty("appId");
            // 根据用户id和应用id查询用户权限
            SysUserDataPermissionDTO dto = new SysUserDataPermissionDTO();
            dto.setUserId(user.getId());
            dto.setAppId(appId);
            R<SysUserDataPermissionVO> sysUserDataPermissionVO = SpringContextUtils.getBean(ISysUserDataPermissionService.class).getDataPermissionByUserIdAndAppId(dto);
            if (sysUserDataPermissionVO == null || sysUserDataPermissionVO.getData() == null || StringUtil.isBlank(sysUserDataPermissionVO.getData().getDataPermission())) {
                throw new GlobalException(String.format("未获取到用户权限，当前用户：%s", user.getRealName()));
            }

            SysUserDataPermissionVO sysUserDataPermission = sysUserDataPermissionVO.getData();
            List<String> listOrg = sysUserDataPermission.getOrgIdList();
            String dataPermission = sysUserDataPermission.getDataPermission();
//        int dataPermission = user.getDataPermission();

            if (String.valueOf(GlobalConst.User.DataPermission.USER).equals(dataPermission)) {
                queryWrapper.eq(GlobalConst.ColumnField.CREATE_BY, user.getId());
            } else if (String.valueOf(GlobalConst.User.DataPermission.ORG).equals(dataPermission)) {
                queryWrapper.eq(GlobalConst.ColumnField.ORG_ID, user.getOrgId());
            } else if (String.valueOf(GlobalConst.User.DataPermission.ALL).equals(dataPermission)) {
//            queryWrapper.eq(GlobalConst.ColumnField.TENANT_ID, user.getTenantId());
            } else if (String.valueOf(GlobalConst.User.DataPermission.ORG_AND_SON).equals(dataPermission)) {
                ISysOrgService orgService = SpringContextUtils.getBean(ISysOrgService.class);
//            Set<String> orgIdSet = orgService.getChildrenIdsByParentId(user.getOrgId());
//            HashSet<String> copyOrgIdSet = Sets.newHashSet(orgIdSet);
//            copyOrgIdSet.add(user.getOrgId());
                queryWrapper.in(GlobalConst.ColumnField.ORG_ID, listOrg);
            } else if (String.valueOf(GlobalConst.User.DataPermission.ORG_CUSTOM).equals(dataPermission)) {
//            ISysDataPermissionService dataPermissionService = SpringContextUtils.getBean(ISysDataPermissionService.class);
//            List<String> orgIdList = dataPermissionService.getOrgIds(user.getId());
                queryWrapper.in(GlobalConst.ColumnField.ORG_ID, listOrg);
            } else {
                throw new GlobalException(String.format("不支持数据权限类型: %s", dataPermission));
            }
        }
    }
}
